package com.nineclock.message.service.impl;

import cn.hutool.core.util.StrUtil;
import com.nineclock.message.service.MessageService;
import com.nineclock.message.utils.JPushManager;
import com.nineclock.system.dto.NcMessageDTO;
import com.nineclock.system.pojo.NcMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    JPushManager jPushManager;
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public Boolean pushSingleMessage(NcMessage message) throws Exception {
//        保存推送消息
        mongoTemplate.save(message);
//        极光推送消息
        return  jPushManager.sendNotificationByAlias(message.getTitle(),message.getContent(),message.getTargets(),null);
    }

    @Override
    public List<NcMessage> findMessageRecord(NcMessageDTO messageDTO) {
//      拼接查询
        Query query=new Query();

        if (messageDTO==null){
            messageDTO = new NcMessageDTO();
        }

        if (StrUtil.isNotEmpty(messageDTO.getId())){
            query.addCriteria(Criteria.where("_id").is(messageDTO.getId()));
        }

        if (StrUtil.isNotEmpty(messageDTO.getType())){
            query.addCriteria(Criteria.where("messageType").is(messageDTO.getType()));
        }

        if (messageDTO.getTargetId()!=null){
            query.addCriteria(Criteria.where("approveUserId").is(messageDTO.getTargetId()));
        }

        if (messageDTO.getUserId()!=null){
            query.addCriteria(Criteria.where("applyUserId").is(messageDTO.getUserId()));
        }

        query.with(Sort.by(Sort.Direction.ASC,"approveStatue"));

        return mongoTemplate.find(query,NcMessage.class);
    }


    @Override
    public void updateMessageWithApproved(String s) {
//        参数为msgId
        Query query=new Query();
        query.addCriteria(Criteria.where("_id").is(s));

        Update update=new Update();
        update.set("useStatus",1);
        update.set("approveStatue",1);

        mongoTemplate.updateFirst(query,update,NcMessage.class);
    }
}
